package com.example.userservice.controller;

import com.example.userservice.common.Result;
import com.example.userservice.entity.User;
import com.example.userservice.entity.dto.UserDtoUpdate;
import com.example.userservice.entity.dto.UserDto;
import com.example.userservice.entity.dto.UserDtoRegisterOrLogin;
import com.example.userservice.entity.dto.UserDtoRetPassword;
import com.example.userservice.entity.vo.UserVo;
import com.example.userservice.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@Tag(name = "用户模块", description = "处理用户注册、登录、信息查询与更新等操作")
public class UserController {
    @Autowired
    private UserService userService;

    // 注册
    @Operation(summary = "注册用户")
    @PostMapping("user/register")
    public Result<String> register(@RequestBody User user, HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        userService.register(user, ip);
        return Result.success("注册成功");
    }

    //登录
    @Operation(summary = "用户登录")
    @PostMapping("user/login")
    public Result<String> login(@RequestBody UserDtoRegisterOrLogin userDto, HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        String token = userService.login(userDto, ip);
        return Result.success(token);
    }

    //获取用户列表
    @Operation(summary = "根据权限获取用户列表")
    @GetMapping("/users")
    public Result<List<UserVo>> getUsers() {
        return Result.success(userService.getUsers());
    }

    //获取指定用户
    @Operation(summary = "根据权限和目标用户ID获取指定用户信息")
    @GetMapping("/user/{userId}")
    public Result<UserVo> getUser(@PathVariable("userId") Long targetUserId) {
        return Result.success(userService.getUser(targetUserId));
    }
    //修改指定用户信息
    @Operation(summary = "根据权限和目标用户Id修改指定用户信息")
    @PutMapping("user/{userId}")
    public Result<String> updateUser(@PathVariable("userId") Long targetUserId, @RequestBody UserDtoUpdate user, HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        userService.updateUser(user, targetUserId,ip);
        return Result.success("修改成功");
    }
    //重置密码
    @Operation(summary = "根据权限和目标用户名修改用户密码")
    @PostMapping("user/password")
    public Result<String> resetPassword(@RequestBody UserDtoRetPassword user, HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        userService.resetPassword(user, ip);
        return Result.success("重置成功");
    }
}
